from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import RegisterSerializer
from utils.base_response import BaseResponse
from utils.commonviews import CommonAPIView
from utils.get_query_params import GetQueryParams
from .models import Account
from utils.redis_pool import POOL
import redis
import uuid


# Create your views here.


class RegisterView(APIView):

    def post(self, request):
        res = BaseResponse()
        # 用序列化器做校验
        ser_obj = RegisterSerializer(data=request.data)
        if ser_obj.is_valid():
            ser_obj.save()
            fieldsList = ['id', 'username', 'head_img', 'name', 'sex', 'age', 'status']
            res.data = {}
            for ft in fieldsList:
                res.data[ft] = ser_obj.data[ft]
            res.msg = '注册成功'
        else:
            res.status = 1
            res.msg = ser_obj.errors
        return Response(res.dict)


class LoginView(APIView):

    def post(self, request):
        res = BaseResponse()
        username = request.data.get("username", "")
        pwd = request.data.get("pwd", "")
        user_objs = Account.objects.filter(username=username, pwd=pwd)
        if not user_objs.count():
            res.status = 1
            res.msg = "用户名或密码错误"
            return Response(res.dict)
        user_obj = user_objs.first()
        # 用户登录成功生成一个token写入redis
        # 写入redis  token : user_id
        conn = redis.Redis(connection_pool=POOL)
        try:
            access_token = user_obj.access_token
            if access_token:
                conn.delete(access_token)
            access_token = uuid.uuid4()
            # conn.set(str(token), user_obj.id, ex=10) # ex=10 过期时间20S
            conn.set(str(access_token), user_obj.id)  # nx=True:key不存在时才写入
            user_obj.access_token = access_token
            user_obj.save()
            ser_obj = RegisterSerializer(user_obj)
            fieldsList = ['id', 'username', 'head_img', 'name', 'sex', 'age', 'status']
            res.data = {}
            for ft in fieldsList:
                res.data[ft] = ser_obj.data[ft]
            res.data['access_token'] = access_token
        except Exception as e:
            res.status = 1
            res.msg = "创建令牌失败"
            res.error = str(e.args)
        return Response(res.dict)


class ExitView(APIView):
    def post(self, request):
        res = BaseResponse()
        token = request.META.get("HTTP_ACCOUNTTOKEN", "")
        conn = redis.Redis(connection_pool=POOL)
        try:
            if token:
                count = conn.delete(token)
                res.data = token
                res.msg = '成功清除token%s个' % count
        except Exception as e:
            res.status = 1
            res.msg = str(e.args)
        return Response(res.dict)


class AccountModelViewSet(CommonAPIView):
    query_set = Account.objects.all().order_by('id')
    serializer_class = RegisterSerializer
    input_get_list = [('account_id', 'id'), ('account_name', 'username__contains'),
                      ('inputObjName', 'username__contains')]
    input_put_list = [('account_id', 'id')]
    input_delete_list = [('account_id', 'id')]
    input_dict = GetQueryParams

    # def put(self, request):
    #     data = request.data
    #     print('data:',data)
    #     return self.update(request)
